// pages/spell_detail/spell_detail.js
var common = require("../../../common/common.js").common;

var leader = require("../../../common/leader.js").leader;

const app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        proceed_id: "",
        //拼单id
        data: "",
        //拼单信息
        hour: "",
        //时
        minute: "",
        //分
        second: "",
        //秒
        buy_count: 1,
        //购买数量
        sku: "",
        sku_info: "",
        alert: 0,
        //规格弹窗
        warrant: true,
        openid: "",
        uid: "",
        is_new: "",
        showInfoTip: false
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        let that = this;
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        // let warrant = common.checkUserWarrant();
        // this.setData({
        //   warrant: warrant,
        // })
        //首次直接进入，拿openid
                if (app.globalData.user) {
            //如果直接拿到openid
            that.setData({
                openid: app.globalData.user.openid,
                uid: app.globalData.user.uid,
                is_new: app.globalData.user.is_new
            });
            // leader.getMyLeaderInfo_aync(that.data.openid, that.data.s_leader[1]).then(() => {
            // })
                } else {
            //回调拿到openid
            app.userInfoReadyCallback = (res => {
                that.setData({
                    openid: res.openid,
                    is_new: res.is_new,
                    uid: res.uid
                });
                // leader.getMyLeaderInfo_aync(that.data.openid, that.data.s_leader[1]).then(() => {
                // })
                        });
        }
        that.setData({
            proceed_id: options.proceed_id
        });
        that.getSpell();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        that.getSpell();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    //获取拼团信息
    getSpell: function() {
        let that = this;
        let proceed_id = that.data.proceed_id;
        common.request({
            endpoint: "Groupbuy/order/spell_info",
            method: "post",
            data: {
                proceed_id: proceed_id
            },
            success: res => {
                that.setData({
                    data: res.extra
                });
                if (res.extra.remaining_time < 0) {
                    wx.showModal({
                        title: "提示",
                        content: "该拼团已结束！",
                        success: function(res) {
                            wx.reLaunch({
                                url: "/pages/index/index"
                            });
                        }
                    });
                }
                if (res.extra.remaining == 0) {
                    wx.showModal({
                        title: "提示",
                        content: "该拼团成功！",
                        success: function(res) {
                            wx.reLaunch({
                                url: "/pages/index/index"
                            });
                        }
                    });
                }
                that.countdown();
            }
        });
    },
    countdown: function() {
        let that = this;
        let times = that.data.data.remaining_time;
        if (times < 0) {
            times = times + 24 * 3600;
        }
        var timer = null;
        timer = setInterval(function() {
            var day = 0, hour = 0, minute = 0, second = 0;
            //时间默认值
                        if (times > 0) {
                hour = Math.floor(times / (60 * 60)) - day * 24;
                minute = Math.floor(times / 60) - day * 24 * 60 - hour * 60;
                second = Math.floor(times) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60;
            }
            if (hour <= 9) hour = "0" + hour;
            if (minute <= 9) minute = "0" + minute;
            if (second <= 9) second = "0" + second;
            that.setData({
                hour: hour,
                minute: minute,
                second: second
            });
            times--;
        }, 1e3);
        if (times <= 0) {
            clearInterval(timer);
        }
    },
    /** 
   * 添加 sku 属性
   */
    addSkuAttribute: function(e) {
        let key_id = parseInt(e.currentTarget.dataset.key_id);
        let value_id = parseInt(e.currentTarget.dataset.value_id);
        let a_key_index = parseInt(e.currentTarget.dataset.a_key_index);
        let a_value_index = parseInt(e.currentTarget.dataset.a_value_index);
        let sku = this.data.sku;
        sku = this.reBlanceSku(sku, key_id, value_id);
        let attribute = this.data.details.sku_attribute;
        attribute = this.selectSku(attribute, a_key_index, a_value_index);
        let sku_info = this.getProductBySku(this.data.details.sku, sku);
        this.setData({
            sku: sku,
            ["details.sku_attribute"]: attribute,
            sku_info: sku_info
        });
    },
    /** 
   * 重平衡 sku
   * key_id: integer
   */
    reBlanceSku: function(sku, key_id, value_id) {
        let sku_lib = sku != "" ? this.splitSku(sku) : [];
        sku_lib = this.addSku(sku_lib, {
            key_id: key_id,
            value_id: value_id
        });
        sku_lib = this.sortSku(sku_lib);
        return this.buildSku(sku_lib);
    },
    /** 
   * 重建 sku
   */
    buildSku: function(sku_lib) {
        return sku_lib.map(item => {
            return item.key_id + "," + item.value_id;
        }).join("|");
    },
    /** 
   * 对选择的 sku 属性进行排序
   */
    sortSku: function(sku_lib) {
        return sku_lib.sort((pre, next) => {
            if (pre.key_id > next.key_id) {
                return 1;
            } else if (pre.key_id < next.key_id) {
                return -1;
            } else {
                return 0;
            }
        });
    },
    /** 
   * 分割现有 sku 成对象数组
   */
    splitSku: function(sku) {
        return sku.split("|").map(sku_tmp => {
            let [key, value] = sku_tmp.split(",");
            const t = {};
            t.key_id = parseInt(key);
            t.value_id = parseInt(value);
            return t;
        });
    },
    /** 
   * 添加一个 sku
   */
    addSku: function(sku_lib, sku) {
        let t = sku_lib.filter(item => {
            if (item.key_id === sku.key_id) {
                return false;
            }
            return true;
        });
        t.push(sku);
        return t;
    },
    /** 
   * 选择 sku
   */
    selectSku: function(attribues, a_index, v_index = 0) {
        if (attribues[a_index]) {
            let values = attribues[a_index].attribute_value;
            values = values.map(item => {
                item.selected = false;
                return item;
            });
            values[v_index].selected = true;
            attribues[a_index].attribute_value = values;
        }
        return attribues;
    },
    /** 
   * 选择单个 sku 属性
   */
    selectSingleSku: function(attribute_value, v_index = 0) {
        attribute_value.map(item => {
            item.selected = false;
            return item;
        });
        attribute_value[v_index].selected = true;
        return attribute_value;
    },
    /**
   * 根据 sku 获取物品
   */
    getProductBySku: function(sku_products, sku) {
        return sku_products[sku];
    },
    save_count: function(e) {
        parseInt;
        this.setData({
            buy_count: parseInt(e.detail.value)
        });
    },
    reduce_count: function() {
        let buy_count = this.data.buy_count;
        if (buy_count > 1) {
            buy_count--;
        }
        this.setData({
            buy_count: buy_count
        });
    },
    add_count: function(e) {
        let buy_count = this.data.buy_count;
        let restrictions = e.currentTarget.dataset.restrictions;
        if (restrictions == 0) {
            buy_count++;
        } else {
            if (buy_count >= restrictions) {
                wx.showModal({
                    title: "提示",
                    content: "本商品限购" + restrictions + "份"
                });
            } else {
                buy_count++;
            }
        }
        this.setData({
            buy_count: buy_count
        });
    },
    //参与拼单
    joinSpell: function() {
        let that = this;
        let data = that.data.data;
        let pro_id = data.pro_id;
        let proceed_id = data.proceed_id;
        common.request({
            endpoint: "Groupbuy/product/price_list",
            method: "post",
            data: {
                id: pro_id,
                proceed_id: proceed_id
            },
            header: {},
            success: function(res) {
                let details = res.extra;
                details.sku_attribute = details.sku_attribute.map(item => {
                    item.attribute_value = that.selectSingleSku(item.attribute_value);
                    return item;
                });
                let sku_attribute = details.sku_attribute;
                let sku = sku_attribute.reduce((s, v) => {
                    s = that.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                    return s;
                }, "");
                let sku_info = that.getProductBySku(details.sku, sku);
                that.setData({
                    sku_info: sku_info,
                    sku: sku,
                    alert: 1,
                    details: res.extra
                });
            },
            fail: function(res) {
                wx.showModal({
                    title: "提示",
                    content: res.message
                });
            }
        });
    },
    //关闭规格弹窗
    close_alert: function(e) {
        let that = this;
        that.setData({
            alert: 0
        });
    },
    confirm: function() {
        console.log(333);
        let that = this;
        let type = 2;
        let sku_info = that.data.sku_info;
        let buy_count = that.data.buy_count;
        let group_id = that.data.data.proceed_id;
        if (sku_info.stock_number >= buy_count) {
            wx.navigateTo({
                url: "/spell/pages/spell_place/spell_place?sku_id=" + sku_info.item_id + "&buy_count=" + buy_count + "&type=" + type + "&group_id=" + group_id
            });
        } else {
            wx.showModal({
                title: "提示",
                content: "库存不足！"
            });
        }
    },
    getUserInfo: function() {
        let that = this;
        common.getUserInfoNew({
            url: "/spell/pages/spell_detail/spell_detail?proceed_id=" + that.data.proceed_id
        });
    },
    continueGetSet: function() {
        let that = this;
        wx.getSetting({
            success(res) {
                console.log(res);
            }
        });
        wx.openSetting({
            success(res) {
                console.log(res);
                if (res.authSetting["scope.userInfo"]) {
                    that.getUserInfo({
                        url: "/spell/pages/spell_detail/spell_detail?proceed_id=" + that.data.proceed_id
                    });
                }
                if (res.authSetting["scope.userLocation"]) {
                    // that.getLocate(that);
                }
                if (that.data.warrant && res.authSetting["scope.userLocation"] || res.authSetting["scope.userInfo"] && res.authSetting["scope.userLocation"]) {
                    that.setData({
                        showInfoTip: false
                    });
                }
            }
        });
    }
});